import { setToken, getToken, removeToken } from '@/utils/auth'
import { loginApi, getInfoApi, getEmpoApi } from '@/api/user'
const state = {
  token: getToken(), // 保存token到vuex
  userInfo: {}
}
const mutations = {
  setToken (state, value) {
    state.token = value
    setToken(value)
  },
  removeToken (state) {
    state.token = null
    removeToken()
  },
  saveUserInfo (state, value) {
    state.userInfo = value
  },
  removeUserInfo (state) {
    state.userInfo = {}
  }
}
const actions = {
  async login (context, payload) {
    try {
      let res = await loginApi(payload)
      if (res.success) {
        context.commit('setToken', res.data)
      }
    } catch (error) {
      return Promise.reject(new Error(error))
    }
  },
  async getUserInfo (context) {
    let res = await getInfoApi()
    let baseRes = await getEmpoApi(res.data.userId)
    context.commit('saveUserInfo', { ...res.data, ...baseRes.data })
  },
  async logout (context) {
    context.commit('removeUserInfo')
    context.commit('removeToken')
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
